// pages/overhaul/overhaul.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';
//去掉末尾的0
const regexp=/(?:\.0*|(\.\d+?)0+)$/;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参来的设备信息
    equipmentInfo:null,
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //用户权限
    authority:null,
    //是否查单个设备的记录
    isOne:false,
    //搜索关键词
    searchValue:'',
    //需要搜索的设备id
    searchIds:[],
    //是否搜索
    isSearchId:false,
    //售后人员
    staffMap: new Map(),
    //当前人员
    user: null,
    //传参
		paramObj: {},		
		//状态筛选
    optionState:[
			{text: '我巡检的', value: 1},
			{text: '所有工单', value: 0}
    ],
		valueState: null,
		//当前人员
		currentStaffId: null,
		//开始时间
    startTime: '开始日期',
    //开始时间选择框
    showStartTime:false,
    //结束时间
    endTime: '结束日期',
    //结束时间选择框
    showEndTime:false,
    //当前时间
    currentStart: new Date().getTime(),
    currentEnd: new Date().getTime(),
    //最小时间
    minDate2:null,
    //最大时间
    maxDate1: new Date().getTime(),
    maxDate2: new Date().getTime(),
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      }
      return value
		},
		//选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //选择框搜索
		valueSearch: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
		let user = app.globalData.userInfo;

    this.setData({
      user: user,
      authority:app.globalData.authority
		})

    if(options.paramObj){
      let obj = JSON.parse(options.paramObj);
      console.log('巡检传参');
      console.log(obj);

      this.setData({
        paramObj: obj,
        equipmentInfo: obj,
        isOne:true
      })
		}

		//平台人员登录的默认查询售后人员巡检的工单
		if(user.departObj[0].type==1){
			this.setData({
				valueState: 1
			})
		}

		//查询售后人员，查完再查巡检列表
		this.getStaffList();
  },

  //获取列表数据
  getList(){
    //从设备列表来的，调用nb接口；从设备工时页面来的，调用另外的接口
    if(this.data.paramObj.fromEquipmentHour){
      this.baseAreaOverhaul();
    }else{
      this.nbList();
    }    
  },

  //获取巡检列表
  nbList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    }); 
		
		let user = this.data.user;
		let dataObj={
			selectFields: ['id','departId','depart','overhaulPersonnel','service','overhaulDate','partMoney','serviceMoney','logisticsMoney','pic','equipmentState','remark','result','equipmentObj','avgTravelCost','isEditPart','costTaxPoint','noAssessmentCost','noAssessmentCostItem','passed','approveLine','userId'],
			sort: {
				overhaulDate: -1
			},
			page: {
				page: this.data.page,
				pageSize: 10
			}
		}

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      if(app.globalData.afterSaleSelf){
        //是否独立售后
        dataObj.appId=app.globalData.myAppId;
      }else{
        dataObj.appId=[2,3,null];
      }
    }else{
      dataObj.appId=[2,3,null];
    }

    if(this.data.isOne){
      dataObj.equipmentId=this.data.equipmentInfo.equipmentId;
      dataObj.nbl=Base64.encode(util.timeFormatDay(new Date()));
    }

    //搜索
    if(this.data.isSearchId){
      dataObj.equipmentId=this.data.searchIds;
		}
		
		//巡检人员
		if(this.data.currentStaffId){
			dataObj.overhaulPersonnel = this.data.currentStaffId;
		}

		//巡检时间
		if(this.data.startTime!='开始日期' && this.data.endTime!='结束日期'){
      dataObj.complex=[{
        and: {
          overhaulDate: {
            ">=": this.data.startTime + " 00:00:00",
            "<=": this.data.endTime + " 23:59:59"
          }
        }
      }]  
		}

		let param = {
      isAuth: true,
      className: 'afterSaleOverhaul',
      data: dataObj
		}

    CommonService.goFindList(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
				let result=res.data.data.result;

        result.forEach(item => {
					//处理费用
					item.self_all = Number(item.partMoney)+Number(item.serviceMoney)+Number(item.logisticsMoney);
					if(item.costTaxPoint){
						item.self_all2 = Number(item.partMoney)+Number(item.costTaxPoint)+Number(item.logisticsMoney);
					}

          //处理图片
          if(item.pic && item.pic!='null'){
            item.pic=JSON.parse(item.pic);
          }
          
          //处理日期
          if(item.overhaulDate){
            item.overhaulDate=util.timeFormat(item.overhaulDate);
          }
         
          //巡检人员和电话
          if(item.overhaulPersonnel){            
            let maps=this.data.staffMap;
            if(maps.get(item.overhaulPersonnel)){
              item.self_staffName=maps.get(item.overhaulPersonnel).name;
              item.self_staffPhone=maps.get(item.overhaulPersonnel).phone;
            }            
					}
					
					//差旅单均摊费用保留两位小数
					if(item.avgTravelCost){
						item.avgTravelCost = (Number(item.avgTravelCost)).toFixed(2).replace(regexp,'$1');
					}

					//是否显示不纳入考核按钮
          let self_showNotAssess = false;					
					
					if(item.passed!=null){
						if (item.passed) {
						}else{
							let curr = user.id === item.userId;
	
							let appStaff = false;
							if (item.approveLine && item.approveLine.length > 0) {
								item.approveLine.forEach(r => {
									if (r.id === user.id) {
										appStaff = true;
									}
								})
							}
	
							self_showNotAssess = curr || appStaff;
						}
					}else{
						self_showNotAssess = true;
					}

          item.self_showNotAssess = self_showNotAssess;
        });

        console.log('巡检列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //从设备工时页面跳转来的，查询巡检
  baseAreaOverhaul(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let param = {
      equipmentId: this.data.paramObj.equipmentId
    }

    //客户按部门查
    let user = app.globalData.userInfo;
    if(user.departObj[0].type == 4){
      param.departId = user.depart;
    }

    CommonService.overhaul(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.list && res.data.data.list.length) {
        let result=res.data.data.list;

        result.forEach(item => {
          //巡检人员
          if(item.overhaulPersonnel){
            item.self_staffName = item.overhaulPersonnel;          
          }
        });

        console.log('巡检列表-从设备工时来的');
        console.log(result);

        this.setData({
          list: result
        })
      }else{
        this.setData({
          showNothing: true
        })  
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.nbList();
  },

  //跳转添加
  goToAdd(){
    wx.navigateTo({
			url: "/pages/overhaulAdd/overhaulAdd?paramObj="+JSON.stringify(this.data.equipmentInfo)
		})
  },

  //跳转编辑
  goToEdit(e){
    let detail=e.currentTarget.dataset.detail;
    wx.navigateTo({
			url: "/pages/overhaulAdd/overhaulAdd?id="+detail.id+"&paramObj="+JSON.stringify(this.data.equipmentInfo)
		})
  },

  //跳转详情
  goToDetail(e){
    let detail=e.currentTarget.dataset.detail;
    wx.navigateTo({
			url: "/pages/overhaulDetail/overhaulDetail?id="+detail.id
		})
  },

  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;

    let newArr=[];
    for(let i=0;i<detail.length;i++){
      newArr.push(detail[i].url);
    }

    wx.previewImage({
      current: src,
      urls: newArr
    })
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail,
    })
  },

  //点击搜索
  onSearch(){
    if(this.data.searchValue){
      //先查出设备id再查巡检记录
      let param = {
        searchKey: this.data.searchValue,
        selectFields:["id"]
      }

      CommonService.goFindEquipmentList(param).then(res=>{
        let arr=[];
        if(res.data.data && res.data.data.result && res.data.data.result.length){
          let result=res.data.data.result;
          result.forEach(item => {
            arr.push(item.id);
          });
        }
        this.setData({
          isSearchId:true,
          searchIds: arr
        })
       
        this.refreshListAndPage();

      }).catch((error) => {
      })
    }else{
      this.setData({
        isSearchId:false
      })
      this.refreshListAndPage();
    }
  },

  //查询售后人员
  getStaffList(){
    let param = {
      isAuth: false,
      className: 'servicePersonal',
      data: {
        searchAll: true,
        selectFields: ['id','serviceName','telephone','userId'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
		}

		//查当前登录人员
		if(this.data.valueState==1){
			param.data.userId = this.data.user.id;
		}

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      if(app.globalData.afterSaleSelf){
        //是否独立售后
        param.data.appId=app.globalData.myAppId;
      }else{
        param.data.appId=[2,3,null];
      }
    }else{
      param.data.appId=[2,3,null];
    }  

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
				let result=res.data.data.result;

				//当前售后人员
				if(result.length==1){
					this.setData({
						currentStaffId: result[0].id
					}) 
				}

        let map=new Map();
        result.forEach(item => {
          map.set(
            item.id,
            {
              name: item.serviceName,
							phone: item.telephone
            }
          );
        });

        console.log('售后人员');
        console.log(map);

        this.setData({
          staffMap: map
        }) 
        
        //获取列表数据
        this.refreshListAndPage();
      }
    }).catch((error) => {
    })
  },

  //跳转配件页面
  goToPart({currentTarget}){
    let detail = currentTarget.dataset.detail;

    let obj={
      id: detail.id
    }

    wx.navigateTo({
      url: "/packageA/pages/overhaulPart/overhaulPart?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转配件更换明细
  goToPartChange({currentTarget}){
    let detail = currentTarget.dataset.detail;

    let obj={
      equipmentId: detail.equipmentId,
      equipmentNo: detail.equipmentObj[0].equipmentNo
    }

    wx.navigateTo({
      url: "/packageA/pages/partDetailList/partDetailList?paramObj="+JSON.stringify(obj)
    })
	},	

	//选择状态
  onChangeState({detail}) {
    this.setData({
      valueState: detail
		})

		if(detail==0){
			this.setData({
				currentStaffId: null
			})
		}
		
		//查询售后人员
		this.getStaffList();
	},
	
	//显示开始时间
  onShowStartTime(){
    this.setData({
      showStartTime: true
    })
  },

  //隐藏开始时间
  onCloseStartTime(){
    this.setData({
      showStartTime: false
    })
  },

  //确认开始时间
  onConfirmStartTime(e) {
    this.setData({
      currentStart: e.detail,
      minDate2:e.detail,
      startTime:util.timeFormatDay(e.detail),
    })
    this.onCloseStartTime();

    if(this.data.endTime!='结束日期'){
      this.refreshListAndPage();
    }
  },

  //显示结束时间
  onShowEndTime(){
    this.setData({
      showEndTime: true
    })
  },

  //隐藏结束时间
  onCloseEndTime(){
    this.setData({
      showEndTime: false
    })
  },

  //确认结束时间
  onConfirmEndTime(e) {
    this.setData({
      currentEnd: e.detail,
      maxDate1:e.detail,
      endTime:util.timeFormatDay(e.detail),
    })
    this.onCloseEndTime();

    if(this.data.startTime!='开始日期'){
      this.refreshListAndPage();
    }
	},
	
	//清除时间
  onCancelTime(){
    this.setData({
      startTime: '开始日期',
      endTime: '结束日期'
    })

    this.onCloseStartTime();
    this.onCloseEndTime();
    this.refreshListAndPage();
	},
	
	//显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //费用项
    if(field=='noAssess'){
      this.setData({
        selectTitle: '费用项',
        showSelectSearch: false
      })
      this.getCostOptions();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //费用项
    if(selectField=='noAssess'){
      obj='popupInfo.noAssessmentCostItem';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
	},
	
	//费用项
	getCostOptions(){
		let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'travelNoAssessmentCostItems',
        selectFields: ['id','name','key','items']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
				let result=res.data.data.result;
				if(result[0].items && result[0].items.length){
					let list = result[0].items;
					let arr=[];
					list.forEach(item => {
						arr.push({
							text: item.name,
							id: item.id,
							obj: item
						});
					});
					
					this.setData({
						selectList: arr
					})
				}
      }
    }).catch((error) => {
    })
	},

	//获取输入的备注
	onGetValueRemark({detail}){
		let val = detail.trim();
		let noAssessmentCostRemark = 'popupInfo.noAssessmentCostRemark'
		this.setData({
			[noAssessmentCostRemark]: val
		})
	},

	//跳转不纳入考核费用审批
  goToNotAssess({currentTarget}){
		let detail = currentTarget.dataset.detail;
		console.log(detail);

    let obj={
      conId: detail.id,
      //服务费
      faCosts: detail.serviceMoney
    }

    wx.navigateTo({
			url: "/packageA/pages/noAssessmentPatrol/noAssessmentPatrol?paramObj="+JSON.stringify(obj)
		})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(!this.data.paramObj.fromEquipmentHour){
      if(this.data.notMore){
        this.setData({
          page: this.data.page + 1
        })
        this.nbList();
      }
    }
  }
})
